#!/bin/sh

# PROVIDE: clash
# REQUIRE: NETWORKING
# KEYWORD: shutdown

. /etc/rc.subr

name="clash"
rcvar=clash_enable
log_file="/var/log/clash.log"

command=/usr/sbin/daemon
command_args="-P /var/run/clash.pid /usr/local/bin/clash -d /usr/local/etc/clash/ >>$log_file"

pidfile=/var/run/${name}.pid

status_cmd=clash_status



: ${clash_enable="NO"}

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> $log_file
}

clash_status()
{
    if [ -n "$rc_pid" ]; then
        log_message "${name} is running as pid $rc_pid."
        echo "${name} is running as pid $rc_pid."
        return 0
    else
        log_message "${name} is not running."
        echo "${name} is not running."
    fi
}

start_clash()
{
    log_message "Starting ${name}..."
    $command $command_args >> $log_file 2>&1 &
    echo $! > /var/run/clash.pid
    log_message "${name} started with pid $(cat /var/run/clash.pid)."
}

stop_clash()
{
    log_message "Stopping ${name}..."
    if [ -f /var/run/clash.pid ]; then
        kill $(cat /var/run/clash.pid)
        rm -f /var/run/clash.pid
        log_message "${name} stopped."
    else
        log_message "No ${name} pid file found."
    fi
}

load_rc_config clash
run_rc_command $1
